package com.ilarele.shopping.client.activities;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.flurry.android.FlurryAgent;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.ilarele.shopping.client.R;
import com.ilarele.shopping.client.util.Global;

public class CustomEditMapView extends MapActivity {
	private static final int E16 = 1000000;
	private MapController mc;
	private GeoPoint touchedPoint;
	private PinMapOverlay myPinOverlay;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map_edit_layout);
		final MapView mapView = (MapView) findViewById(R.id.mapview);

		myPinOverlay = new PinMapOverlay();
		mapView.getOverlays().add(myPinOverlay);

		mapView.setBuiltInZoomControls(true);
		mapView.setSatellite(false);
		//
		mc = mapView.getController();
		mc.setZoom(18);

		mapView.setClickable(true);
		mapView.setEnabled(true);
		mapView.displayZoomControls(true);

		final MyLocationOverlay myLocationOverlay = new MyLocationOverlay(this,
				mapView);
		mapView.getOverlays().add(myLocationOverlay);
		myLocationOverlay.enableCompass();

		Intent receiveIntent = getIntent();
		boolean hasLocation = receiveIntent.getBooleanExtra("hasLocation",
				false);
		if (hasLocation) {
			double longitude = receiveIntent.getDoubleExtra("longitude",
					Global.DEFAULT_LONGITUDE);
			double latitude = receiveIntent.getDoubleExtra("latitude",
					Global.DEFAULT_LATITUDE);
			touchedPoint = new GeoPoint(getE6(latitude), getE6(longitude));
			mc.animateTo(touchedPoint);
		} else {
			myLocationOverlay.enableMyLocation();
			myLocationOverlay.runOnFirstFix(new Runnable() {
				public void run() {
					touchedPoint = myLocationOverlay.getMyLocation();
					mc.animateTo(touchedPoint);
					System.out.println("runOnFirstFix " + touchedPoint);
				}
			});
		}

		final Button saveBtn = (Button) findViewById(R.id.map_save);
		saveBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent();
				if (touchedPoint != null) {
					double latitude = (double) touchedPoint.getLatitudeE6() / 1E6;
					double longitude = (double) touchedPoint.getLongitudeE6() / 1E6;
					String location = "";
					intent.putExtra("latitude", latitude);
					intent.putExtra("longitude", longitude);

					Geocoder gc = new Geocoder(CustomEditMapView.this, Locale
							.getDefault());
					try {
						List<Address> addresses = gc.getFromLocation(latitude,
								longitude, 1);
						StringBuilder sb = new StringBuilder();

						if (addresses.size() > 0) {
							Address address = addresses.get(0);

							for (int i = 0; i < address
									.getMaxAddressLineIndex(); i++)
								sb.append(address.getAddressLine(i)).append(
										"\n");

							sb.append(address.getCountryName());
						}
						location = sb.toString();
					} catch (IOException e) {
						Log.e("log", "Error retriving address from geopoint!");
					}

					intent.putExtra("location", location);
					setResult(RESULT_OK, intent);
				}
				finish();
			}
		});
	}

	private int getE6(double degree) {
		return (int) (degree * E16);
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	class PinMapOverlay extends com.google.android.maps.Overlay {
		@Override
		public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
				long when) {
			super.draw(canvas, mapView, shadow);
			if (touchedPoint != null) {
				// translate the GeoPoint to screen pixels
				Point screenPts = new Point();
				mapView.getProjection().toPixels(touchedPoint, screenPts);

				// add the marker
				Bitmap bmp = BitmapFactory.decodeResource(getResources(),
						R.drawable.pin);

				int width = bmp.getWidth();
				int height = bmp.getHeight();
				canvas.drawBitmap(bmp, screenPts.x - width / 2, screenPts.y
						- height / 2, null);
			}
			return true;
		}

		@Override
		public boolean onTouchEvent(MotionEvent event, MapView mapView) {
			if (event.getAction() == MotionEvent.ACTION_UP) {
				touchedPoint = mapView.getProjection().fromPixels(
						(int) event.getX(), (int) event.getY());
				return true;
			}
			return super.onTouchEvent(event, mapView);
		}
	}

	@Override
	public void onStart() {
		super.onStart();
		if (!Global.DEBUG_MODE)
			FlurryAgent.onStartSession(this, Global.FLURRY_ID);
	}

	@Override
	public void onStop() {
		super.onStop();
		if (!Global.DEBUG_MODE)
			FlurryAgent.onEndSession(this);
	}
}